from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from ..models.user import User
from ..models.tool import Tool
from bson.objectid import ObjectId
import datetime
from functools import wraps

admin_bp = Blueprint('admin', __name__)

# 管理员权限检查装饰器
def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not current_user.is_authenticated or not current_user.is_admin():
            flash('你没有权限访问此页面', 'danger')
            return redirect(url_for('main.index'))
        return f(*args, **kwargs)
    return decorated_function


@admin_bp.route('/')
@login_required
@admin_required
def index():
    """管理面板首页"""
    # 获取统计数据
    user_count = User.count_users()
    tool_count = Tool.count_tools()
    
    # 获取最近5个用户
    recent_users = User.get_recent_users(limit=5)
    
    # 获取最受欢迎的工具
    popular_tools = Tool.get_popular_tools(limit=5)
    
    return render_template('admin/index.html', 
                           user_count=user_count,
                           tool_count=tool_count,
                           recent_users=recent_users,
                           popular_tools=popular_tools)


@admin_bp.route('/users')
@login_required
@admin_required
def users():
    """用户管理页面"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    # 获取用户列表，带分页
    users, total_pages = User.get_users_paginated(page=page, per_page=per_page)
    
    return render_template('admin/users.html', 
                           users=users,
                           page=page,
                           per_page=per_page,
                           total_pages=total_pages)


@admin_bp.route('/users/<user_id>')
@login_required
@admin_required
def user_detail(user_id):
    """用户详情页面"""
    user = User.find_by_id(ObjectId(user_id))
    if not user:
        flash('用户不存在', 'danger')
        return redirect(url_for('admin.users'))
    
    return render_template('admin/user_detail.html', user=user)


@admin_bp.route('/users/<user_id>/edit', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_user(user_id):
    """编辑用户信息"""
    user = User.find_by_id(ObjectId(user_id))
    if not user:
        flash('用户不存在', 'danger')
        return redirect(url_for('admin.users'))
    
    if request.method == 'POST':
        # 更新用户信息
        username = request.form.get('username')
        email = request.form.get('email')
        role = request.form.get('role')
        
        # 验证用户名和邮箱是否已被其他用户使用
        if username != user.username and User.find_by_username(username):
            flash('用户名已被使用', 'danger')
            return render_template('admin/edit_user.html', user=user)
        
        if email != user.email and User.find_by_email(email):
            flash('邮箱已被使用', 'danger')
            return render_template('admin/edit_user.html', user=user)
        
        # 更新用户信息
        user.username = username
        user.email = email
        user.role = role
        user.save()
        
        flash('用户信息已更新', 'success')
        return redirect(url_for('admin.user_detail', user_id=user_id))
    
    return render_template('admin/edit_user.html', user=user)


@admin_bp.route('/users/<user_id>/delete', methods=['POST'])
@login_required
@admin_required
def delete_user(user_id):
    """删除用户"""
    user = User.find_by_id(ObjectId(user_id))
    if not user:
        flash('用户不存在', 'danger')
        return redirect(url_for('admin.users'))
    
    # 不允许删除自己
    if user.id == current_user.id:
        flash('不能删除自己的账户', 'danger')
        return redirect(url_for('admin.users'))
    
    # 执行删除
    User.delete_user(user.id)
    
    flash('用户已删除', 'success')
    return redirect(url_for('admin.users'))


@admin_bp.route('/tools')
@login_required
@admin_required
def tools():
    """工具管理页面"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    # 获取工具列表，带分页
    tools, total_pages = Tool.get_tools_paginated(page=page, per_page=per_page)
    
    return render_template('admin/tools.html', 
                           tools=tools,
                           page=page,
                           per_page=per_page,
                           total_pages=total_pages)


@admin_bp.route('/tools/new', methods=['GET', 'POST'])
@login_required
@admin_required
def new_tool():
    """创建新工具"""
    if request.method == 'POST':
        # 获取表单数据
        name = request.form.get('name')
        slug = request.form.get('slug')
        category = request.form.get('category')
        description = request.form.get('description')
        icon = request.form.get('icon')
        is_featured = bool(request.form.get('is_featured'))
        config = request.form.get('config', '{}')
        
        # 验证数据
        if not name or not slug or not category:
            flash('名称、标识和分类不能为空', 'danger')
            return render_template('admin/new_tool.html')
        
        # 检查slug是否已存在
        if Tool.find_by_slug(slug):
            flash('此工具标识已被使用', 'danger')
            return render_template('admin/new_tool.html')
        
        # 创建工具
        tool = Tool(
            name=name,
            slug=slug,
            category=category,
            description=description,
            icon=icon,
            is_featured=is_featured,
            config=config,
            created_at=datetime.datetime.now(),
            updated_at=datetime.datetime.now(),
            usage_count=0
        )
        tool.save()
        
        flash('工具创建成功', 'success')
        return redirect(url_for('admin.tools'))
    
    return render_template('admin/new_tool.html')


@admin_bp.route('/tools/<tool_id>')
@login_required
@admin_required
def tool_detail(tool_id):
    """工具详情页面"""
    tool = Tool.find_by_id(ObjectId(tool_id))
    if not tool:
        flash('工具不存在', 'danger')
        return redirect(url_for('admin.tools'))
    
    return render_template('admin/tool_detail.html', tool=tool)


@admin_bp.route('/tools/<tool_id>/edit', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_tool(tool_id):
    """编辑工具信息"""
    tool = Tool.find_by_id(ObjectId(tool_id))
    if not tool:
        flash('工具不存在', 'danger')
        return redirect(url_for('admin.tools'))
    
    if request.method == 'POST':
        # 获取表单数据
        name = request.form.get('name')
        slug = request.form.get('slug')
        category = request.form.get('category')
        description = request.form.get('description')
        icon = request.form.get('icon')
        is_featured = bool(request.form.get('is_featured'))
        config = request.form.get('config', '{}')
        
        # 验证数据
        if not name or not slug or not category:
            flash('名称、标识和分类不能为空', 'danger')
            return render_template('admin/edit_tool.html', tool=tool)
        
        # 检查slug是否已被其他工具使用
        existing_tool = Tool.find_by_slug(slug)
        if existing_tool and str(existing_tool.id) != tool_id:
            flash('此工具标识已被使用', 'danger')
            return render_template('admin/edit_tool.html', tool=tool)
        
        # 更新工具信息
        tool.name = name
        tool.slug = slug
        tool.category = category
        tool.description = description
        tool.icon = icon
        tool.is_featured = is_featured
        tool.config = config
        tool.updated_at = datetime.datetime.now()
        tool.save()
        
        flash('工具信息已更新', 'success')
        return redirect(url_for('admin.tool_detail', tool_id=tool_id))
    
    return render_template('admin/edit_tool.html', tool=tool)


@admin_bp.route('/tools/<tool_id>/delete', methods=['POST'])
@login_required
@admin_required
def delete_tool(tool_id):
    """删除工具"""
    tool = Tool.find_by_id(ObjectId(tool_id))
    if not tool:
        flash('工具不存在', 'danger')
        return redirect(url_for('admin.tools'))
    
    # 执行删除
    Tool.delete_tool(tool.id)
    
    flash('工具已删除', 'success')
    return redirect(url_for('admin.tools'))


@admin_bp.route('/logs')
@login_required
@admin_required
def logs():
    """系统日志页面"""
    # 这里可以实现系统日志查看功能，比如操作日志、错误日志等
    return render_template('admin/logs.html')


@admin_bp.route('/settings', methods=['GET', 'POST'])
@login_required
@admin_required
def settings():
    """系统设置页面"""
    if request.method == 'POST':
        # 更新系统设置
        # 这里可以实现系统设置的保存功能
        flash('系统设置已更新', 'success')
        return redirect(url_for('admin.settings'))
    
    return render_template('admin/settings.html') 